package com.caocaog.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caocaog.market.constant.MarketConstant;
import com.caocaog.market.entity.ShopPromo;
import com.caocaog.market.entity.ShopPromoBase;
import com.caocaog.market.entity.ShopPromoHis;
import com.caocaog.market.mapper.ShopPromoMapper;
import com.caocaog.market.service.ShopPromoHisService;
import com.caocaog.market.service.ShopPromoService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品促销信息
 *
 * @author chechen
 * @date 2021-11-20
 */
@Service
@Transactional
@RequiredArgsConstructor
public class ShopPromoServiceImpl extends ServiceImpl<ShopPromoMapper, ShopPromo> implements ShopPromoService {

    private final ShopPromoHisService shopPromoHisService;
    private final CommonAPI commonAPI;

    @Override
    public IPage<ShopPromo> queryShopPromoPage(Page<ShopPromo> page, ShopPromo shopPromo) {
        this.handleShopPromoByUserType(shopPromo, (LoginUser) SecurityUtils.getSubject().getPrincipal());
        return super.baseMapper.queryShopPromoPage(page, shopPromo);
    }

    @Override
    public String addShopPromo(ShopPromo shopPromo) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        this.handleShopPromoByUserType(shopPromo, loginUser);
        shopPromo.setCreateTime(new Date());
        shopPromo.setCreateBy(((LoginUser) SecurityUtils.getSubject().getPrincipal()).getUsername());
        shopPromo.setDelFlag(CommonConstant.DEL_FLAG_0);
        shopPromo.setLockVersion(1);
        shopPromo.setStatus(1);

        // 新增商品促销信息操作
        super.baseMapper.insert(shopPromo);
        if (shopPromo.getId() == null)
            throw new JeecgBootException("新增商品促销信息失败");

        // 添加到商品促销历史信息里
        ShopPromoHis shopPromoHis = new ShopPromoHis(shopPromo);
        this.shopPromoHisService.addShopPromoHis(shopPromoHis);
        return shopPromo.getId();
    }

    /*private int trapRainWater(int[][] heightMap) {
        // 如果有边长为2，则接不到雨水
        if (heightMap.length <= 2 || heightMap[0].length <= 2) {
            return 0;
        }
        int m = heightMap.length;
        int n = heightMap[0].length;
        // 访问过的节点
        boolean[][] visit = new boolean[m][n];
        // 小顶堆，且放入的是数组，比较高度
        PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> o1[1] - o2[1]);

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (i == 0 || i == m - 1 || j == 0 || j == n - 1) {
                    // i * n + j代表第几个
                    // 0    1   2    //4*3d
                    // 3    4   5
                    // 6    7   8
                    // 9    10  11
                    pq.offer(new int[]{i * n + j, heightMap[i][j]});
                    visit[i][j] = true;
                }
            }
        }
        int res = 0;
        // 通过for循环4次则能用i和i+1定位【上，右，下，左】
        int[] dirs = {-1, 0, 1, 0, -1};
        // 如果小顶堆为空
        while (!pq.isEmpty()) {
            // 小顶堆出栈
            int[] curr = pq.poll();
            for (int k = 0; k < 4; ++k) {
                // 第几个取位置，第/n则是行数index，第%n则是第几列数index
                int nx = curr[0] / n + dirs[k];
                int ny = curr[0] % n + dirs[k + 1];
                // 不越界并且没有被访问过
                if (nx >= 0 && nx < m && ny >= 0 && ny < n && !visit[nx][ny]) {
                    // 如果当前位置大于周围，则可以注水,并且访问过之后高度为注水后的高度     ※因为这是从最小开始的，比最小还小的则可以接雨水
                    if (curr[1] > heightMap[nx][ny]) {
                        res += curr[1] - heightMap[nx][ny];
                        pq.offer(new int[]{nx * n + ny, curr[1]});
                    } else { // 如果大于则更新边界
                        pq.offer(new int[]{nx * n + ny,heightMap[nx][ny]});
                    }
                    // 将访问过的位置设置为true
                    visit[nx][ny] = true;
                }
            }
        }
        return res;
    }*/

    /**
     * 根据用户类型处理信息发布实体数据
     *
     * @param shopPromo 信息发布实体
     * @param loginUser   当前登录用户
     */
    private void handleShopPromoByUserType(ShopPromo shopPromo, LoginUser loginUser) {
        // 根据用户类型判断
        if (MarketConstant.USER_TYPE_SITE.equals(loginUser.getUserType())) {
            if (StringUtils.isBlank(loginUser.getSiteId()))
                throw new JeecgBootException("用户暂未绑定分站, realName-> " + loginUser.getRealname());
            // 分站类型默认 查询该分站下的数据/插入分站
            shopPromo.setSiteId(loginUser.getSiteId());
        } else if (MarketConstant.USER_TYPE_MERCHANT.equals(loginUser.getUserType())) {
            if (StringUtils.isBlank(loginUser.getMerchantId()))
                throw new JeecgBootException("用户暂未绑定商家, realName-> " + loginUser.getRealname());
            if (StringUtils.isBlank(loginUser.getCurrentSelectedShopId()))
                throw new JeecgBootException("请选择店铺后再次添加");
            String siteId = commonAPI.getSiteIdByMerchantId(loginUser.getMerchantId());
            if (StringUtils.isBlank(siteId))
                throw new JeecgBootException("商家暂未绑定分站, realName-> " + loginUser.getRealname());
            // 商家类型默认 查询该商家下的数据/插入商家
            shopPromo.setSiteId(siteId);
            shopPromo.setMerchantId(loginUser.getMerchantId());
            shopPromo.setShopId(loginUser.getCurrentSelectedShopId());
        }
    }

    @Override
    public int updateShopPromo(ShopPromo shopPromo) {
        shopPromo.setUpdateTime(new Date());
        shopPromo.setUpdateBy(((LoginUser) SecurityUtils.getSubject().getPrincipal()).getUsername());
        shopPromo.setDelFlag(null);

        // 更新商品促销信息操作
        int updateRecordCount = super.baseMapper.updateById(shopPromo);
        if (updateRecordCount == 0)
            throw new JeecgBootException("更新商品促销信息失败, id-> " + shopPromo.getId());

        // 添加到历史记录里
        ShopPromoHis shopPromoHis = new ShopPromoHis(shopPromo);
        this.shopPromoHisService.addShopPromoHis(shopPromoHis);
        return updateRecordCount;
    }

    @Override
    public int deleteShopPromo(String id) {
        int deleteRecordCount = super.baseMapper.deleteById(id);
        if (deleteRecordCount == 0)
            throw new JeecgBootException("删除商品促销信息失败, id-> " + id);
        return deleteRecordCount;
    }

    @Override
    public int deleteBatchShopPromo(List<String> ids) {
        int deleteRecordCount = super.baseMapper.deleteBatchIds(ids);
        if (deleteRecordCount < ids.size())
            throw new JeecgBootException(
                    String.format("批量删除商品促销信息失败, deleteRecordCount-> %s, ids.size()-> %s, ids-> %s",
                            deleteRecordCount, ids.size(), ids));
        return deleteRecordCount;
    }

    @Override
    public int shopPromoStatusChange(String id) {
        int statusChangeRecordCount = super.baseMapper.update(null, Wrappers.<ShopPromo>lambdaUpdate()
                .setSql("status = !status, lock_version = lock_version + 1")
                .set(ShopPromo::getUpdateTime, LocalDateTime.now())
                .set(ShopPromo::getUpdateBy, ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getUsername())
                .eq(ShopPromo::getId, id));
        if (statusChangeRecordCount == 0)
            throw new JeecgBootException("商品促销信息状态变更失败, id-> " + id);

        // 添加到历史记录里
        ShopPromoHis shopPromoHis = new ShopPromoHis(super.baseMapper.selectById(id));
        this.shopPromoHisService.addShopPromoHis(shopPromoHis);
        return statusChangeRecordCount;
    }

    @Override
    public List<ShopPromo> selectShopPromoByShopId(String shopId) {
        return super.baseMapper.selectList(new LambdaQueryWrapper<ShopPromo>()
                        .eq(ShopPromo::getShopId, shopId)
                        .eq(ShopPromo::getStatus, 0) // 默认查询开启
        );
    }

    @Override
    public List<String> getShopPromoByShopId(String shopId) {
        return this.selectShopPromoByShopId(shopId)
                .stream().map(ShopPromoBase::getName).collect(Collectors.toList());
    }
}
